﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Collections;
using System.Xml;
using log4net;
using System.Globalization;

namespace QualityRpt.Utils
{
    /// <summary>
    /// StringUtils 的摘要说明
    /// </summary>
    public class StringUtils
    {
        static ILog logger = LogManager.GetLogger("StringUtils");
        public StringUtils()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 清楚字符串中的html标签
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string ExtractText(string html)
        {
            if (html == null && html.Trim() == string.Empty)
            {
                return string.Empty;
            }
            html = Regex.Replace(html, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            return html;
        }
        public static string ContentToXml(string content)
        {
            if (content == null)
            {
                return string.Empty;
            }
            String xml = content.Replace("&", "&#38;");
            xml = xml.Replace("<", "&#60;");
            xml = xml.Replace(">", "&#62;");
            xml = xml.Replace("'", "&#39;");
            xml = xml.Replace("\"", "&#34;");
            xml = xml.Replace(",", "&#44;");
            return xml;
        }
        public static string XmlToContent(string xml)
        {
            if (xml == null)
            {
                return string.Empty;
            }
            string content = xml.Replace("&#38;","&");
            content = content.Replace("&#60;", "<");
            content = content.Replace("&#62;", ">");
            content = content.Replace("&#39;", "'");
            content = content.Replace("&#34;", "\"");
            content = content.Replace("&#44;", ",");
            return content;
        }
        #region 取汉字拼音
        /// <summary>
        /// /// 取单个字符的拼音声母///
        /// /// 2004-11-30/// </summary>/// <param name="c">要转换的单个汉字</param>
        /// /// <returns>拼音声母</returns>
        public static string GetPYChar(string c)
        {
            //加入特殊的字的处理
            if (c.Trim() == "薇")
            {
                return "w";
            }
            //按ascii码进行一般处理
            byte[] array = new byte[2];
            array = System.Text.Encoding.Default.GetBytes(c);
            long i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
            if (i < 0xB0A1) return "*";
            if (i < 0xB0C5) return "a";
            if (i < 0xB2C1) return "b";
            if (i < 0xB4EE) return "c";
            if (i < 0xB6EA) return "d";
            if (i < 0xB7A2) return "e";
            if (i < 0xB8C1) return "f";
            if (i < 0xB9FE) return "g";
            if (i < 0xBBF7) return "h";
            if (i < 0xBFA6) return "g";
            if (i < 0xC0AC) return "k";
            if (i < 0xC2E8) return "l";
            if (i < 0xC4C3) return "m";
            if (i < 0xC5B6) return "n";
            if (i < 0xC5BE) return "o";
            if (i < 0xC6DA) return "p";
            if (i < 0xC8BB) return "q";
            if (i < 0xC8F6) return "r";
            if (i < 0xCBFA) return "s";
            if (i < 0xCDDA) return "t";
            if (i < 0xCEF4) return "w";
            if (i < 0xD1B9) return "x";
            if (i < 0xD4D1) return "y";
            if (i < 0xD7FA) return "z";
            return "*";
        }
        /// <summary>
        /// 汉字转拼音缩写
        /// 黑色头发---hstf    
        /// </summary>
        /// <returns>拼音缩写</returns>
        public static string GetPYString(string str)
        {
            string tempStr = "";
            foreach (char c in str)
            {
                if (c.ToString().Trim() != string.Empty)
                {
                    if ((int)c >= 33 && (int)c <= 126)
                    {//字母和符号原样保留           
                        tempStr += c.ToString();
                    }
                    else
                    {//累加拼音声母     
                        tempStr += GetPYChar(c.ToString());
                    }
                }
            }
            return tempStr;
        }
        #endregion
        /// <summary>
        /// 截断中英文
        /// </summary>
        public static string CutString(string s, int l)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = s.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }
                if (nLength > l)
                {
                    break;
                }
            }
            if (s.Length > l)
            {
                sb.Append("...");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 将一个秒数换成时分秒
        /// </summary>
        /// <param name="totalSecond"></param>
        /// <returns></returns>
        public static string GetHMS(long totalSecond)
        {
            int h = Convert.ToInt32(totalSecond / 3600);
            int m = Convert.ToInt32((totalSecond - h * 3600) / 60);
            int s = Convert.ToInt32(totalSecond - h * 3600 - m * 60);
            string rt = h.ToString() + ":" + m.ToString() + ":" + s.ToString();
            return rt;
        }
        public static long GetTimeLong(string hms)
        {
            string[] arrayLength = hms.Split(new char[] { ':' });
            long vllength = 0L;
            if (arrayLength.Length == 3)
            {
                string[] sArray = arrayLength[2].Split(new char[] { ',', '.' });//秒后面还有单位
                vllength = int.Parse(arrayLength[0]) * 3600 + int.Parse(arrayLength[1]) * 60 + int.Parse(sArray[0]);
            }
            else if (arrayLength.Length == 2)
            {
                string[] sArray = arrayLength[1].Split(new char[] { ',', '.' });//秒后面还有单位
                vllength = int.Parse(arrayLength[0]) * 60 + int.Parse(sArray[0]);
            }
            else if (arrayLength.Length == 1)
            {
                string[] sArray = arrayLength[0].Split(new char[] { ',', '.' });//秒后面还有单位
                vllength = int.Parse(sArray[0]);
            }
            return vllength;
        }
        /// <summary>
        /// 获得形如3小时以前,20分钟以前这样的字符串
        /// </summary>
        public static string FormatHMS(DateTime dt)
        {
            StringBuilder sbHMS = new StringBuilder();
            TimeSpan ts = DateTime.Now - dt;
            if (ts.TotalDays > 365)//大于一年
            {
                double dyears = ts.TotalDays / 365;
                sbHMS.Append(Math.Floor(dyears) + " 年以前");
            }
            else if (ts.TotalDays > 30)
            {
                double dmonth = ts.TotalDays / 30;
                sbHMS.Append(Math.Floor(dmonth) + "个月以前");
            }
            else if (ts.TotalDays > 1)
            {
                sbHMS.Append(Math.Floor(ts.TotalDays) + "天以前");
            }
            else if (ts.TotalHours > 1)
            {
                sbHMS.Append(Math.Floor(ts.TotalHours) + "小时以前");
            }
            else if (ts.TotalMinutes > 1)
            {
                sbHMS.Append(Math.Floor(ts.TotalMinutes) + "分钟以前");
            }
            else if (ts.TotalSeconds > 1)
            {
                sbHMS.Append(Math.Floor(ts.TotalSeconds) + "秒钟以前");
            }
            return sbHMS.ToString();
        }
        /// <summary>
        /// 隐藏ip的后两位
        /// </summary>
        /// <param name="_ip"></param>
        /// <returns></returns>
        public static string FormatIp(object _ip)
        {
            string[] ipArray = _ip.ToString().Split(new char[] { '.' });
            string rt = string.Empty;
            if (ipArray.Length > 1)
            {
                rt = ipArray[0] + "." + ipArray[1] + ".*.*";
            }
            else
            {
                rt = "0.0.*.*";
            }
            return rt;
        }
        public static string GetDomain(string uri)
        {
            System.Text.RegularExpressions.Regex regx = new Regex(@"http://.*?/");
            string temp = regx.Match(uri).Value;
            temp = temp.Substring(7);
            return temp;
        }
        public static string[] GetHtmlImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);

            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表
            foreach (Match match in matches)
            {
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            }
            return sUrlList;
        }
        private static string[] punc_zhs = new string[] { "，", "。", "！", "？", "”" };//中文段落结束符
        private static string[] punc_ens = new string[] { ",", ".", "!", "?", "\"" };//英文段落结束符
        /// <summary>
        /// 获得中文字幕的lrc形式
        /// </summary>
        public static string GetLrcTextZh(string text)
        {
            string[] lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (lines.Length < 3)
            {
                lines = text.Split(new string[] { "。" }, StringSplitOptions.RemoveEmptyEntries);
            }
            StringBuilder sb_text = new StringBuilder();
            for (int i = 0; i < lines.Length; i++)
            {
                string[] lrc_line = SplitTimeAndText(lines[i]);
                string end_s = string.Empty;
                bool has_end_pun = false;
                for (int k = 0; k < punc_zhs.Length; k++)
                {
                    if (lrc_line[1].Trim().EndsWith(punc_zhs[k]))
                    {
                        has_end_pun = true;
                    }
                }
                if (!has_end_pun) { end_s = "。"; }
                sb_text.Append("<span style='display:none;'>" + lrc_line[0] + "</span> " + lrc_line[1] + end_s + "\r\n");
            }
            return sb_text.ToString();
        }
        public static string GetLrcTextEn(string text)
        {
            string[] lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (lines.Length < 3)
            {
                lines = text.Split(new string[] { ". " }, StringSplitOptions.RemoveEmptyEntries);
            }
            StringBuilder sb_text = new StringBuilder();
            for (int i = 0; i < lines.Length; i++)
            {
                string[] lrc_line = SplitTimeAndText(lines[i]);
                string end_s = string.Empty;
                bool has_end_pun = false;
                for (int k = 0; k < punc_ens.Length; k++)
                {
                    if (lrc_line[1].Trim().EndsWith(punc_ens[k]))
                    {
                        has_end_pun = true;
                    }
                }
                if (!has_end_pun) { end_s = ". "; }
                sb_text.Append("<span style='display:none;'>" + lrc_line[0] + "</span> " + lrc_line[1] + end_s + "\r\n");
            }
            return sb_text.ToString();
        }
        /// <summary>
        /// 将歌词模式转换成TimedText字幕格式
        /// </summary>
        public static string ConvertLrcToTT(string lrc)
        {
            StringBuilder sbHtml = new StringBuilder();
            string[] lines = lrc.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            sbHtml.Append("<tt xml:lang=\"en\" xmlns=\"http://www.w3.org/2006/10/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/10/ttaf1#style\">");
            sbHtml.Append("<head>");
            sbHtml.Append("<layout/>");
            sbHtml.Append("<styling>");
            sbHtml.Append("<style id=\"1\" tts:textAlign=\"right\"/>");
            sbHtml.Append("<style id=\"2\" tts:color=\"transparent\"/>");
            sbHtml.Append("<style id=\"3\" style=\"2\" tts:backgroundColor=\"white\"/>");
            sbHtml.Append("<style id=\"4\" style=\"2 3\" tts:fontSize=\"14\"/>");
            sbHtml.Append("</styling>");
            sbHtml.Append("</head>");
            sbHtml.Append("<body>");
            sbHtml.Append("<div xml:id=\"captions\">");
            //
            if (lines.Length < 1)
            {
                sbHtml.Append("<p begin=\"0:0:0\" end=\"0:0:50\">字幕缺失.</p>");
            }
            else
            {
                for (int i = 0; i < lines.Length; i++)
                {
                    string tt_begin = string.Empty; string tt_end = string.Empty; string tt_text = string.Empty;
                    string[] ttArray = SplitTimeAndText(lines[i]);
                    tt_begin = ttArray[0]; tt_text = ttArray[1].Replace(">", " ");
                    if (i < lines.Length - 1)
                    {
                        string[] tt_end_array = SplitTimeAndText(lines[i + 1]);
                        tt_end = tt_end_array[0];
                    }
                    tt_begin = tt_begin.Replace("：", ":").Replace("。", ".");
                    tt_end = tt_end.Replace("：", ":").Replace("。", ".");
                    sbHtml.Append("<p begin=\"" + tt_begin + "\" end=\"" + tt_end + "\">" + ExtractText(tt_text) + "</p>");
                }
            }
            //结束
            sbHtml.Append("</div></body></tt>");
            return sbHtml.ToString();
        }
        /// <summary>
        /// 合并两个lrc,可用于中英文
        /// </summary>
        /// <param name="lrc_1"></param>
        /// <param name="lrc_2"></param>
        /// <returns></returns>
        public static string CombineLrc(string lrc_zh, string lrc_en)
        {
            StringBuilder sbHtml = new StringBuilder();
            string[] lines_1 = lrc_zh.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string[] lines_2 = lrc_en.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (lines_1.Length < 3)
            {
                lines_1 = lrc_zh.Split(new string[] { "。" }, StringSplitOptions.RemoveEmptyEntries);
            }
            if (lines_2.Length < 3)
            {
                lines_2 = lrc_en.Split(new string[] { ". " }, StringSplitOptions.RemoveEmptyEntries);
            }
            int max_length = lines_1.Length > lines_2.Length ? lines_1.Length : lines_2.Length;
            for (int i = 0; i < max_length; i++)
            {
                if (lines_1.Length > i)
                {
                    sbHtml.Append(lines_1[i]);
                }
                if (lines_2.Length > i)
                {
                    string[] line_2_array = SplitTimeAndText(lines_2[i]);
                    sbHtml.Append("&lt;br/&gt;" + line_2_array[1] + "\r\n");
                }
            }
            return sbHtml.ToString();
        }
        /// <summary>
        /// 分离lrc模式的时间和字幕文本格式
        /// </summary>
        /// <param name="line">00:00:22 对白</param>
        /// <returns>array[0]=00:00:22 array[1]=对白</returns>
        public static string[] SplitTimeAndText(string line)
        {
            string[] ttArray = new string[2] { string.Empty, string.Empty };
            int text_index = line.Trim().IndexOf(" ");//找到第一个空格
            if (text_index > 0)
            {
                ttArray[0] = line.Trim().Substring(0, text_index).Trim();
                if (ttArray[0].Contains(":"))
                {
                    ttArray[1] = line.Trim().Substring(text_index, line.Trim().Length - text_index).Trim();
                }
                else
                {
                    ttArray[0] = string.Empty;
                    ttArray[1] = line.Trim();
                }
            }
            else
            {
                ttArray[1] = line.Trim();
            }
            return ttArray;
        }
        /// <summary>
        /// 替换关键字为红色
        /// </summary>
        /// <param name="keycontent">原始内容</param>
        /// <param name="k">关键字，支持多关键字</param>
        /// <returns>String</returns>
        /// <author>haver Guo</author>
        public static string Highlightkeywords(string keycontent, string k)
        {
            if (k == null || k.Trim() == string.Empty)
            {
                return keycontent;
            }
            string resultstr = keycontent;
            if (k.Trim().IndexOf(' ') > 0)
            {
                string[] myArray = k.Split(' ');
                for (int i = 0; i < myArray.Length; i++)
                {
                    resultstr = resultstr.Replace(myArray[i].ToString(), "<font color=#FF0000>" + myArray[i].ToString() + "</font>");
                }
                return resultstr;
            }
            else
            {
                return resultstr.Replace(k, "<font color=#FF0000>" + k + "</font>");
            }
        }
        /// <summary>
        /// 是否还有中文字符
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static bool ContainChinese(string content)
        {
            Regex r = new Regex(@"[\u4e00-\u9fa5]");
            return r.IsMatch(content);
        }
        /// <summary>
        /// 是否还有日文
        /// </summary>
        public static bool ContainJapanese(string content)
        {
            Regex r = new Regex(@"[\u0800-\u4e00]");
            return r.IsMatch(content);
        }
        /// <summary>
        /// 将Unicode编码转换为汉字字符串
        /// </summary>
        /// <param name="str">Unicode编码字符串</param>
        /// <returns>汉字字符串</returns>
        public static string ToGB2312(string str)
        {
            string rt = string.Empty;
            rt = Regex.Replace(str, "\\\\u\\w{4}",
                delegate(Match m)
                {
                    return ((char)(int.Parse(m.Value.Substring(2), System.Globalization.NumberStyles.HexNumber))).ToString();
                });
            return rt;
        }
        /// <summary>
        /// 转换成百分比
        /// </summary>
        /// <param name="dra"></param>
        /// <returns></returns>
        public static string FormatRatio(object dra)
        {
            string rt = "0";
            if (dra != null && dra != DBNull.Value)
            {
                decimal drt = Convert.ToDecimal(dra) * 100;
                rt = drt.ToString("f2");
            }
            return rt;
        }
        /// <summary>
        /// 将秒换算成时分秒的格式
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FormatHMS(long totalSecond)
        {
            StringBuilder sb_text = new StringBuilder();
            int h = Convert.ToInt32(totalSecond / 3600);
            int m = Convert.ToInt32((totalSecond - h * 3600) / 60);
            int s = Convert.ToInt32(totalSecond - h * 3600 - m * 60);
            if (h > 0)
            {
                sb_text.Append(h.ToString() + "小时");
            }
            if (m > 0)
            {
                sb_text.Append(m.ToString() + "分");
            }
            if (s > 0)
            {
                sb_text.Append(s.ToString() + "秒");
            }
            if (sb_text.ToString().Trim() == string.Empty)
            {
                sb_text.Append("0秒");
            }
            return sb_text.ToString();
        }
        /// <summary>
        /// 为字符串加单引号
        /// </summary>
        /// <param name="sqlIn"></param>
        /// <returns></returns>
        public static string FormatStrInSql(string sqlIn)
        {
            string[] strArray = sqlIn.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder sbSql = new StringBuilder();
            for (int i = 0; i < strArray.Length; i++)
            {
                if (i > 0)
                {
                    sbSql.Append(",");
                }
                sbSql.Append("'" + strArray[i] + "'");
            }
            return sbSql.ToString();
        }
    }
}